<!--
 * @Author: early-autumn
 * @Date: 2020-05-18 11:07:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-07-03 17:36:27
-->
<template>
  <el-dialog
    :visible="value"
    :width="width"
    center
    :append-to-body="true"
    @close="handleClose"
  >
    <div v-loading="loading">
      <iframe
        v-if="value"
        ref="iframe"
        :class="loading && 'visible'"
        class="iframe"
        title="咿呀口腔"
        :src="src"
      />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handlePrint">点击打印</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  name: 'PrintPanel',
  model: {
    prop: 'value',
    event: 'close',
  },
  props: {
    width: {
      type: String,
      default: '800px',
    },
    value: Boolean,
    path: {
      type: String,
      default: '',
    },
    data: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      loading: false,
    }
  },
  computed: {
    src() {
      return `${window.location.origin}${this.path}`
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.init()
        window.addEventListener('message', this.message, false)
      } else {
        window.removeEventListener('message', this.message, false)
      }
    },
  },
  methods: {
    init() {
      this.loading = true
    },
    message(event) {
      const data =
        typeof event.data === 'string' ? JSON.parse(event.data) : event.data
      if (data.type === 'PrintPage:start') {
        event.source.postMessage(
          JSON.stringify({
            type: 'PrintPanel:data',
            data: this.data,
          })
        )
      }
      if (data.type === 'PrintPage:end') {
        try {
          this.$refs.iframe.height = +(
            event.source.document.documentElement.scrollHeight ||
            event.source.document.body.scrollHeight
          )
          event.source.document.body.height = 'auto'
        } finally {
          this.loading = false
        }
      }
    },
    handleClose() {
      this.$emit('close', false)
    },
    handlePrint() {
      this.$refs.iframe.contentWindow.print()
      this.handleClose()
    },
  },
}
</script>

<style lang="scss" scoped>
.iframe {
  width: 100%;
  border: 0 none;
  pointer-events: none;
}
.visible {
  visibility: hidden;
}
</style>
